#pragma once

#include<iostream>
#include"Socket.hpp"
#include<sys/select.h>
#include<sys/time.h>

using namespace std;

static const uint16_t defaultport = 8080;
static const int fd_num_max = sizeof(fd_set) * 8;
int defaultfd = -1;

class SelectServer
{
public:
    SelectServer(uint16_t port = defaultport)
    :_port(port)
    {
        for(int i = 0; i<fd_num_max;i++)
            fd_array[i] = defaultfd;
    }

    ~SelectServer()
    {}
public:
    bool Init()
    {
        _listensock.Socket();
        _listensock.Bind(_port);
        _listensock.Listen();

        return true;
    }

    void Accepter()
    {
        string clientip;
        uint16_t clientport = 0;
        
        int sock = _listensock.Accept(&clientip, &clientport);
        if(sock < 0) return;
        lg(Info, "accept success, ip: %s, port: %d", clientip.c_str(), clientport);

        // char buffer[1024];
        // ssize_t n = read(sock, buffer, sizeof(buffer));//这里可以直接读吗？不可以
        int pos = 1;
        for(; pos < fd_num_max; pos++)
        {
            if(fd_array[pos] != defaultfd) continue;
            else break;
        }
        if(pos == fd_num_max)
        {
            lg(Warning, "server is full, get new fd faided");
            close(sock);
        }
        else
        {
            fd_array[pos] = sock;
        }
    }

    void Recver(int fd, int i)
    {
        char buffer[1024];
        ssize_t n = read(fd, buffer, sizeof(buffer)-1);
        if(n > 0)
        {
            buffer[n] = 0;
            cout<<"get a message: "<<buffer<<endl;
        }
        else if(n == 0)
        {
            lg(Info, "client quit, close fd is : %d", fd);
            close(fd);
            fd_array[i] = defaultfd;
        }
        else
        {
            lg(Warning, "read error, close fd is : %d", fd);
            close(fd);
            fd_array[i] = defaultfd;
        }
    }

    void Dispatcher(fd_set &rfds)
    {
        for(int i = 0; i < fd_num_max; i++)
        {
            int fd = fd_array[i];
            if(fd == defaultfd) continue;

            //当事件就绪时，有连接请求和接收请求，如何判断呢？
            if(fd == _listensock.GetFd() && FD_ISSET(fd, &rfds))//获取新连接情况
            {
                Accepter();//连接管理器
            }
            else//读事件就绪
            {
                Recver(fd, i);
            }
        }
    }


    void Start()
    {
        int listensock = _listensock.GetFd();
        fd_array[0] = listensock;

        while(true)
        {
            fd_set rfds;
            FD_ZERO(&rfds);
            
            int maxfd = fd_array[0];
            for(int i = 0; i<fd_num_max; i++)
            {
                if(fd_array[i] == defaultfd) continue;
                FD_SET(fd_array[i], &rfds);
                //这里还有一个问题，如果前面的描述符已经退出，这样设置下面会返回错误信息
                if(maxfd < fd_array[i]) maxfd = fd_array[i];
            }
            //这里不能使用accept,新连接来了，相当于读时间到来

            FD_SET(listensock, &rfds);

            struct timeval timeout = {1, 0};
            //如果事件就绪，上层不提醒，select会一直提醒你
            // fd_set wfds;
            // fd_set exception;
            int n = select(maxfd + 1, &rfds, nullptr, nullptr, &timeout);
            switch(n)
            {
                case 0:
                    cout<<"time out, timeout: "<<timeout.tv_sec<<endl;
                    break;
                case -1:
                    cerr<<"select error"<<endl;
                    break;
                default:
                    //有事件就绪
                    cout<<"get a new link"<<endl;
                    Dispatcher(rfds);
                    break;
            }
        }
    }

    void PrintFd()
    {
        cout<<"online fd list:"<<endl;
        for(int i = 0; i < fd_num_max; i++)
            if(fd_array[i] != defaultfd)
                cout<<fd_array[i]<<" ";
    }
private:
    Sock _listensock;
    uint16_t _port;
    int fd_array[fd_num_max];
    //int wfd_array[fd_num_max];
};

